package org.example.c_0_002;

import org.junit.Test;

/**
 * 演示默认线程不可见带来的问题，及Volatile解决方案。
 */
public class T_Volatile_Visibility {
    private /*volatile*/ boolean flag = true;

    public void m(){
        System.out.println(Thread.currentThread().getName()+":执行开始");
        while(flag){

        }
        System.out.println(Thread.currentThread().getName()+":执行结束");
    }

    @Test
    public void run(){
        T_Volatile_Visibility t = new T_Volatile_Visibility();
        Thread t1 = new Thread(t::m, "t1");
        t1.start();
        try {
            Thread.sleep(1000L);
            t.flag = false;
            Thread.sleep(9000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
